/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.istia.gesstages.actions;

import fr.istia.gesstages.metier.Offer;
import fr.istia.gesstages.metier.User;
import fr.istia.gesstages.util.DateFormat;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.struts2.ServletActionContext;

public class OfferAction extends ParentAction {

    // user
    private User user;
    // offer
    private List<Offer> offersList = new ArrayList<Offer>();
    private Offer offer;
    private int id;
    private Date dateEnvoi;
    private Date dateOffre;
    private File pdf;
    private String pdfFileName;
    private String pdfContentType;
    // Pour le retour de la page précédente
    private String back;

    public String deleteOffer() {
        try {
            offer = metier.findOfferById(id);
            metier.deleteOffer(offer);
            return SUCCESS;
        } catch (Exception ex) {
            addActionError(getText("error.offer.delete") + " : " + ex.toString());
            return ERROR;
        }
    }

    private String repertoirePdf() {
        ServletContext context = ServletActionContext.getServletContext();
        return context.getRealPath("/pdf/");
    }

    private void saveFile() {
        String dateFormatee = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss").format(new Date());
        this.pdfFileName = this.pdfFileName.replace(".pdf", "") + dateFormatee + ".pdf";
        File savePdf = new File(repertoirePdf(), this.pdfFileName);
        this.pdf.renameTo(savePdf);
        offer.setFile(this.pdfFileName);
    }

    private void deleteFile() {
        File file = new File(repertoirePdf(), offer.getFile());
        file.delete();
    }

    public String validateEdit() {
        try {
            user = (User) session.get("user");
            offer.setDateEnvoi(DateFormat.getGregorianDate(dateEnvoi));
            offer.setDateOffre(DateFormat.getGregorianDate(dateOffre));
            offer.setOwner(user);
            offer.setArchive(false);
            pdfFileName = pdfFileName == null ? "" : pdfFileName;
            if (!pdfFileName.equals("")) {
                deleteFile();
                saveFile();
            }
            this.offer = metier.updateOffer(offer);
            if (offer == null) {
                return INPUT;
            } else {
                return SUCCESS;
            }
        } catch (Exception ex) {
            addFieldError("error.offer.edit", ex.toString());
            return ERROR;
        }
    }

    public String findOffer() {
        try {
            this.offer = metier.findOfferById(id);
            dateEnvoi = offer.getDateEnvoi().toGregorianCalendar().getTime();
            dateOffre = offer.getDateOffre().toGregorianCalendar().getTime();
            if (offer == null) {
                return ERROR;
            } else {
                return SUCCESS;
            }
        } catch (Exception ex) {
            addActionError(getText("error.offer.find") + " : " + ex.toString());
            return ERROR;
        }
    }

    public String validateCreate() {
        offer.setArchive(false);
        offer.setMaitre("");
        // upload du fichier pdf
        if (this.pdfFileName != null) {
            saveFile();
        } else {
            offer.setFile("");
        }
        try {
            offer.setDateEnvoi(DateFormat.getGregorianDate(dateEnvoi));
            offer.setDateOffre(DateFormat.getGregorianDate(dateOffre));
            user = (User) session.get("user");
            offer.setOwner(user);
            if (metier.createOffer(offer) == null) {
                return INPUT;
            } else {
                return SUCCESS;
            }
        } catch (Exception ex) {
            addActionError(getText("error.offer.create") + " : " + ex.toString());
            return ERROR;
        }
    }

    public String updateOffersList() {
        if (getIsAdmin()) {
            this.back = "offersAdmin";
            offersList = metier.findOffersNotArchived();
            Collections.sort(offersList, new BeanComparator("id"));
            return SUCCESS;
        } else {
            return findOffersNotApplied();
        }
    }

    public String findOffersNotApplied() {
        try {
            user = (User) session.get("user");
            offersList = metier.findOffersNotAppliedBy(user);
        } catch (Exception ex) {
            addActionError(getText("error.offer.find.not.applied") + " : " + ex.toString());
            return ERROR;
        }
        return SUCCESS;
    }

    public InputStream getInputStream() {
        try {
            this.offer = metier.findOfferById(id);
            ServletContext servletContext = ServletActionContext.getServletContext();
            return servletContext.getResourceAsStream("/pdf/" + (String) this.offer.getFile());
        } catch (Exception ex) {
            addActionError(getText("error.offer.donwnload") + " : " + ex.toString());
        }
        return null;
    }
    
    public String updateOffersListbyArchives(){
         try {
            this.back = "offersArchive";
            this.offersList = metier.findOffersArchived();
         }catch (Exception ex) {
            addActionError(getText("error.offer.archive.find") + " : " + ex.toString());
        }
         return SUCCESS;
    }
    
    public String updateOffersListbyNotArchived(){
         try {
            this.offersList = metier.findOffersNotArchived();
         }catch (Exception ex) {
            addActionError(getText("error.offer.archive.find") + " : " + ex.toString());
        }
         return SUCCESS;
    }
    
    public String archiveAllOffers(){
        try {
            this.offersList = metier.findOffersNotArchived();
            for(Offer offerToArchive: offersList){
                offerToArchive.setArchive(true);
                metier.updateOffer(offerToArchive);
            }
            this.offersList = metier.findOffersNotArchived();
         }catch (Exception ex) {
            addActionError(getText("error.offer.archive.all") + " : " + ex.toString());
        }
        return SUCCESS;
    }

    public List<Offer> getOffersList() {
        return offersList;
    }

    public void setOffersList(List<Offer> offersList) {
        this.offersList = offersList;
    }

    public Offer getOffer() {
        return offer;
    }

    public void setOffer(Offer offer) {
        this.offer = offer;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Date getDateEnvoi() {
        return dateEnvoi;
    }

    public void setDateEnvoi(Date dateEnvoi) {
        this.dateEnvoi = dateEnvoi;
    }

    public Date getDateOffre() {
        return dateOffre;
    }

    public void setDateOffre(Date dateOffre) {
        this.dateOffre = dateOffre;
    }

    public File getPdf() {
        return pdf;
    }

    public void setPdf(File pdf) {
        this.pdf = pdf;
    }

    public String getPdfContentType() {
        return pdfContentType;
    }

    public void setPdfContentType(String pdfContentType) {
        this.pdfContentType = pdfContentType;
    }

    public String getPdfFileName() {
        return pdfFileName;
    }

    public void setPdfFileName(String pdfFileName) {
        this.pdfFileName = pdfFileName;
    }

    public String getBack() {
        return back;
    }

    public void setBack(String back) {
        this.back = back;
    }
}
